package com.stock.controller;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.stock.model.ImageResponse;
import com.stock.service.StockService;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api")
public class StockController {
    
    @Autowired
    private StockService stockService;
    
    @PostMapping("/upload")
    public List<String> uploadImages(
            @RequestParam("images") MultipartFile[] files,
            @RequestParam("type") String type) {
        return stockService.saveUploadedFiles(files, type);
    }
    
    @GetMapping("/random-image")
    public ImageResponse getRandomImage(HttpSession session) {
        return stockService.getRandomImage(session.getId());
    }
    
    @GetMapping("/previous-image")
    public ResponseEntity<ImageResponse> getPreviousImage(HttpSession session) {
        ImageResponse image = stockService.getPreviousImage(session.getId());
        if (image == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(image);
    }
    
    @GetMapping("/next-image")
    public ImageResponse getNextImage(HttpSession session) {
        return stockService.getNextImage(session.getId());
    }
    
    @GetMapping("/images/{type}/{filename}")
    public ResponseEntity<Resource> getImage(
            @PathVariable String type,
            @PathVariable String filename) throws IOException {
        Resource file = stockService.loadImageAsResource(type, filename);
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(file);
    }
} 